package com.cold.legendary.bprocess.common.utils;

import com.cold.legendary.bprocess.common.constance.BErrorCodeEnum;
import com.cold.legendary.bprocess.common.exception.BProcessException;
import org.hibernate.validator.HibernateValidator;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import java.util.Iterator;
import java.util.Set;

/**
 * @author cold
 * @since 2023/3/10
 */
public class ValidateBeanUtils {

    /**
     * 注解参数校验
     *
     * @param object 验证对象
     */
    public static void validateAnnotation(Object object) {

        ValidatorFactory validatorFactory = Validation.byProvider(HibernateValidator.class)
                .configure().addProperty("hibernate.validator.fail_fast", "true")
                .buildValidatorFactory();
        Validator validator = validatorFactory.getValidator();

        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
        Iterator<ConstraintViolation<Object>> iterator = constraintViolations.iterator();

        // 是否有检验失败
        while (iterator.hasNext()) {
            // 检验失败消息
            throw new BProcessException(BErrorCodeEnum.BIZ_ERROR, iterator.next().getMessage());
        }
    }
}
